package com.nannybear.Communication;

import android.util.Log;

import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ExecutionException;

/**
 * @brief Send message from NannyBear_App to NannyBear.
 */
public class ProxyRobot implements Observer{
    /********** DECLARATIONS **********/
    private Connection connection;

    /************ METHODS ************/
    /**
     * @brief Constructor.
     */
    public ProxyRobot(Connection connection){
        this.connection = connection;
    }

    /**
     * @brief Send a asynchronous message.
     */
    private void sendMessage(String message){
       //TODO : verifier que le message est bien transmis = ack de réponse
        EmissionTask emissionTask = new EmissionTask(this.connection);
        try{
            emissionTask.execute(message).get();
        }catch (ExecutionException ex){
            Log.e("ProxyRobot", "Interrupted task : "+ex.getCause());
        }catch (InterruptedException ex){
            Log.e("ProxyRobot", "Aborted task : "+ex.getMessage());
        }
    }

    /**
     * @brief Send the light threshold (between dark and dim).
     */
    public void sendLightThresholdDarkDim(int lightThresholdDarkDim){
        String message = String.valueOf(Protocol.LIGHT_THRESHOLD_DARK_DIM)+"/"+String.valueOf(lightThresholdDarkDim);
        sendMessage(message);
    }

    /**
     * @brief Send the light threshold (between dim and bright).
     */
    public void sendLightThresholdDimBright(int lightThresholdDimBright){
        String message = String.valueOf(Protocol.LIGHT_THRESHOLD_DIM_BRIGHT)+"/"+String.valueOf(lightThresholdDimBright);
        sendMessage(message);
    }

    /**
     * @brief Send the light threshold (between dark and dim).
     */
    public void sendSoundThreshold(int soundThreshold){
        String message = String.valueOf(Protocol.SOUND_THRESHOLD)+"/"+String.valueOf(soundThreshold);
        sendMessage(message);
    }

    /**
     * @brief update information.
     */
    public void update(Observable obs, Object obj){
        String name = obs.getClass().getSimpleName();
        if(name.equalsIgnoreCase("SoundThreshold")){
            sendSoundThreshold((int)obj);
        }
        if(name.equalsIgnoreCase("LightThreshold")){
            String storage[] = obj.toString().split("/");
            sendLightThresholdDarkDim(Integer.parseInt(storage[0]));
            sendLightThresholdDimBright(Integer.parseInt(storage[1]));
        }
    }

    /*********** ACCESSORS ***********/
    public Connection getConnection() {
        return connection;
    }
}
